//
//  DrawView.m
//  SimpleDraw
//
//  Created by David Hatch on 12/6/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "DrawView.h"
#import "PreferenceController.h"
#import "AppController.h"


@implementation DrawView

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
		draw = NO;
		NSRect bounds = [self bounds];
		NSPoint center = NSMakePoint(bounds.origin.x, bounds.origin.y);
        currentPoint = center;
		pathsToDraw = [[NSMutableArray alloc]init];
		pathColors = [[NSMutableArray alloc]init];
		NSLog(@"Bg color is %@", [preferenceController bgColor]);
    }
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
	[nc addObserver:self
		   selector:@selector(redraw:) name:TESDBgColorChange object:nil];
	return self;
}

- (void)drawRect:(NSRect)rect {
    NSRect bounds = [self bounds];
	[[preferenceController bgColor] set];
	[NSBezierPath fillRect:bounds];
	if(draw == YES)
	{
		unsigned i;
		for(i=0; i < [pathsToDraw count]; i++) {
			[[pathColors objectAtIndex:i] set];
			NSLog(@"color to use is %@", [pathColors objectAtIndex:i]);
			[[pathsToDraw objectAtIndex:i] fill];
		}
	}
}

- (IBAction)clear:(id)sender
{
	[pathsToDraw removeAllObjects];
	[pathColors removeAllObjects];
	draw = YES;
	[self setNeedsDisplay:YES];
}

-(void)redraw:(NSNotification *)note
{
	[self setNeedsDisplay:YES];
}

-(void)handleMouse:(NSEvent *)event
{
	NSPoint p = [event locationInWindow];
	currentPoint = [self convertPoint:p fromView:nil];
	draw = YES;
	size = [preferenceController penSize];
	int halfOfSize = size/2;
	NSRect rectToDraw = NSMakeRect(currentPoint.x-halfOfSize, currentPoint.y-halfOfSize, size, size);
	NSBezierPath * path = [NSBezierPath bezierPathWithOvalInRect:rectToDraw];
	NSColor *c = [preferenceController fgColor];
	[self insertColorInPathColors:c];
	[self insertObjectInPathsToDraw:path];
}
#pragma mark Mouse Events

- (void)mouseDown:(NSEvent *)event
{
	[self handleMouse:event];
}

- (void)mouseDragged:(NSEvent *)event
{
	[self handleMouse:event];
}

- (void)mouseUp:(NSEvent *)event
{
	[self handleMouse:event];
}

#pragma mark Accessors

@synthesize size;
- (void)insertObjectInPathsToDraw:(NSBezierPath *)path
{
	[pathsToDraw addObject:path];
	NSLog(@"Path Inserted in PathsToDraw is %@", path);
	draw = YES;
	[self setNeedsDisplay:YES];
	NSLog(@"There are %d objects in pathsToDraw", [pathsToDraw count]);
}

- (void)insertColorInPathColors:(NSColor *)color
{
	[pathColors addObject:color];
	NSLog(@"color inserted in pathColors is %@", color);
	NSLog(@"there are %d objects in pathColors", [pathColors count]);
}

@end
